<template>
  <div class="">
    <HeaderView />
  <div class="search-container">
    
    <div class="breadcrumb">
      <a-breadcrumb>
        <a-breadcrumb-item ><img src="../../assets/home.png" alt="首页" ><span @click="GOtoIndex" style="cursor:pointer">首页</span></a-breadcrumb-item>
        <a-breadcrumb-item>课程搜索</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <div class="filter-section">
      <!-- 专题筛选 -->
      <div class="filter-group">
    <span>专题：</span>
    <button @click="selectFilter('Topic', '')" :class="{ active: activeTopic == '' }">全部专题</button>
    <button
      v-for="item in courseDetail" 
      :key="item.subjectId"
      @click="selectFilter('Topic', item.subjectId)"
      :class="{ active: activeTopic == item.subjectId }"
    >
      {{ item.title }}
    </button>
  </div>

      <!-- 类型筛选 -->
      <div class="filter-group">
        <span>类型：</span>
        <button
          v-for="type in types"
          :key="type.id"
          @click="selectFilter('Type', type.id)"
          :class="{ active: activeType === type.id }"
        >
          {{ type.name }}
        </button>
      </div>

      <!-- 方式筛选 -->
      <div class="filter-group">
        <span>方式：</span>
        <button
          v-for="method in methods"
          :key="method.id"
          @click="selectFilter('Method', method.id)"
          :class="{ active: activeMethod === method.id }"
        >
          {{ method.name }}
        </button>
      </div>
    </div>

    <div v-if="loading" class="status">加载中...</div>
    <div v-else-if="error" class="status error">{{ error }}</div>
    <div v-else-if="courses.length === 0" class="status">
      <h2>暂无相关搜索结果，换个关键词试试吧 : )</h2>
      
    </div>


    <div class="coursebox">
      <div 
        v-for="item in courses" 
        :key="item.courseId" 
        class="course"
        @click="goToDetail(item.courseId)"  
      >
       <div class="courseboximg"><img :src="item.coverFileUrl" ></div>
        <div class="courseTitle"> {{ item.courseTitle }}</div>
        <div class="learningNum">共{{ item.subSectionNum }}节课|{{ item.learningNum }}人报名</div>
        <div id="isFree">
          <span v-if="item.isFree == 1">免费</span>
          <span v-else-if="item.isDiscount == 1 && item.isFree == 0">
            <span class='red'>￥{{ item.discountPrice }}</span> <del>￥{{ item.coursePrice }}</del>
          </span>
          <span v-else>
            <span class='red'>￥{{ item.coursePrice }}</span>
          </span>
        </div>
      </div>
    </div>

    <div class="pagination" v-if="total > 0">
      <button @click="prevPage" :disabled="pageNum <= 1">上一页</button>
      <span>第 {{ pageNum }} 页 / 共 {{ totalPages }} 页</span>
      <button @click="nextPage" :disabled="pageNum >= totalPages">下一页</button>
    </div>
  </div>
  
  <FooterView />
</div>
</template>

<script>

import { searchCourses,getDetail } from '@/api/request';
import HeaderView from '@/views/search/components/headerView.vue';
import FooterView from '@/components/footerView.vue';


export default {
  name: 'SearchView',
  data() {
    return {
      courseDetail: [],
      types: [
        { id: '', name: '全部类型' },
        { id: 'free', name: '免费课程' },
        { id: 'boutique', name: '精品课程' },
        { id: 'pay', name: '付费课程' },
        { id: 'discount', name: '折扣课程' }
      ],
      methods: [
        { id: '', name: '全部方式' },
        { id: 'live', name: '直播课程' },
        { id: 'recorded', name: '录播课程' }
      ],
      activeTopic: '',
      activeType: '',
      activeMethod: '',
      courses: [],
      loading: false,
      error: null,
      pageNum: 1,
      pageSize: 15,
      total: 0,
     searchKeyword: ''
    }
    
  },
  watch: {
  '$route.query': {
    immediate: true,
    handler(newVal) {
      this.searchKeyword = newVal.keyword || ''; 
      this.activeTopic = newVal.topic || '';
      this.activeType = newVal.type || '';
      this.activeMethod = newVal.method || '';
      this.pageNum = parseInt(newVal.page) || 1;
      this.fetchCourses(); 
    }
  }
},


  components: {
      HeaderView,
      FooterView, 
    },
  computed: {
    totalPages() {
      return Math.ceil(this.total / this.pageSize) || 0;
    }
  },
  methods: {
    selectFilter(filterType, value) {
    this[`active${filterType}`] = this[`active${filterType}`] === value ? '' : value;
    this.resetPageAndFetch();
  },
  
  resetPageAndFetch() {
  this.pageNum = 1;
  const newQuery = {
    ...this.$route.query,
    topic: this.activeTopic,
    type: this.activeType,
    method: this.activeMethod,
    page: this.pageNum
  };

  if (JSON.stringify(newQuery) !== JSON.stringify(this.$route.query)) {
    this.$router.push({ query: newQuery }).catch(err => {
      if (err.name !== 'NavigationDuplicated') {
        throw err;
      }
    });
  } else {
    this.fetchCourses();
  }
},
   
    async fetchCourses() {
      this.loading = true;
      this.error = null;
      try {
        const res = await searchCourses(
          this.searchKeyword || '', 
          this.activeType || '', 
          this.activeTopic || '', 
          this.activeMethod || '',
          this.pageNum, 
          this.pageSize 
        );
        
        if (res?.code === 0) {
          this.courses = res.courseList || [];
          this.total = res.total || 0;
        } else {
          throw new Error(res?.message || '获取课程列表失败');
        }
      } catch (err) {
        console.error('请求失败:', err);
        this.error = err.message;
        this.courses = [];
        this.total = 0;
      } finally {
        this.loading = false;
      }
    },
    
    prevPage() {
      if (this.pageNum > 1) {
        this.pageNum--;
        this.fetchCourses();
      }
    },
    
    nextPage() {
      if (this.pageNum < this.totalPages) {
        this.pageNum++;
        this.fetchCourses();
      }
    },
  
    goToDetail(courseId) {
      const url = this.$router.resolve({
        path: `/detail/${courseId}`,
        query: {
          id: courseId
        }
      });
      window.open(url.href, '_blank');
    },
    GOtoIndex(){
      const url = this.$router.resolve({
        path: `/`,
        query: {
 
        }
      });
      window.open(url.href, '_blank');
        },
    
  },
  created() {
    this.searchKeyword = this.$route.query.keyword || '';
    this.fetchCourses();
    getDetail({"enable": "1"}).then(res => {
      if (res?.code === 0) {
        this.courseDetail = res.rows || [];
      }
    })
  }
}

</script>



<style scoped lang="scss">

.course {
  position: relative;
  overflow: hidden;
}

.course img {
  transition: transform 0.3s;
}


.isFree {
  font-weight: bold;
  margin-top: 10px;
}

.red {
  color: #f5222d;
  font-size: 1.1em;
}

.pagination button:not(:disabled):hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

.status {
  min-height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.search-container {
  max-width: 1200px;
  margin: 20px auto 0 auto;
 
}

.breadcrumb {
  margin-bottom: 20px;
}

.breadcrumb img {
  width: 16px;
  height: 16px;
  margin-right: 4px;
  vertical-align: middle;
}

.filter-section {
  margin: 20px 0;
  padding: 20px;
  background: #f5f5f5;
  border-radius: 8px;
}

.filter-group {
  margin: 20px 0;
}

.filter-group span {
  margin-right: 10px;
  font-weight: bold;
}

.filter-group button {
  margin:2px;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
  outline: none; 
  background: #f5f5f5;
}

.filter-group button.active {
  background: #00cf8c;
  color: white;
  border-color: #00cf8c;
}

.coursebox {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.course {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
}

.course:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.courseboximg {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 5px;
  margin-bottom: 10px;
     img{
   width: 100%;
   height: 150px;

     }
}

.courseSubTitle {
  font-size: 16px;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.learningNum {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.red {
  color: #f5222d;
}

.pagination {
  margin-top: 30px;
  text-align: center;
}

.pagination button {
  margin: 0 10px;
  padding: 5px 15px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.pagination button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.status {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

.status.error {
  color: #f5222d;
}

.reset-btn {
  margin-top: 15px;
  padding: 6px 15px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>